using System.IO;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// NewProjectDialog.xaml 的交互逻辑
    /// </summary>
    public partial class NewProjectDialog : Window
    {
        public string ProjectName { get; private set; } = string.Empty;
        public string ProjectType { get; private set; } = "Novel";
        public string ProjectPath { get; private set; } = string.Empty;
        public string ProjectDescription { get; private set; } = string.Empty;
        public int TargetChapterCount { get; private set; } = 1000;
        public int TargetWordsPerChapter { get; private set; } = 6500;
        public string CreativeDirection { get; private set; } = string.Empty;

        public bool IsConfirmed { get; private set; } = false;

        public NewProjectDialog()
        {
            InitializeComponent();
            InitializeDefaults();
        }

        private void InitializeDefaults()
        {
            // 设置默认项目路径
            var defaultPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "DocumentCreation");
            ProjectPathTextBox.Text = defaultPath;

            // 监听项目类型变化
            ProjectTypeComboBox.SelectionChanged += ProjectTypeComboBox_SelectionChanged;
            
            // 设置默认项目名称
            ProjectNameTextBox.Text = $"新项目_{DateTime.Now:yyyyMMdd_HHmmss}";
        }

        private void ProjectTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ProjectTypeComboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                var projectType = selectedItem.Tag?.ToString() ?? "Normal";
                
                // 根据项目类型显示或隐藏小说设置
                if (NovelSettingsExpander != null)
                {
                    NovelSettingsExpander.Visibility = projectType == "Novel" ? Visibility.Visible : Visibility.Collapsed;
                }
            }
        }

        private void BrowseFolder_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFolderDialog
            {
                Title = "选择项目文件夹"
            };

            if (!string.IsNullOrEmpty(ProjectPathTextBox.Text))
            {
                dialog.InitialDirectory = ProjectPathTextBox.Text;
            }

            if (dialog.ShowDialog() == true)
            {
                ProjectPathTextBox.Text = dialog.FolderName;
            }
        }

        private void CreateProject_Click(object sender, RoutedEventArgs e)
        {
            // 验证输入
            if (string.IsNullOrWhiteSpace(ProjectNameTextBox.Text))
            {
                MessageBox.Show("请输入项目名称", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                ProjectNameTextBox.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(ProjectPathTextBox.Text))
            {
                MessageBox.Show("请选择项目路径", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 获取选中的项目类型
            var selectedItem = ProjectTypeComboBox.SelectedItem as ComboBoxItem;

            // 验证小说项目的特殊设置
            if (selectedItem?.Tag?.ToString() == "Novel")
            {
                if (!int.TryParse(TargetChapterCountTextBox.Text, out int chapterCount) || chapterCount <= 0)
                {
                    MessageBox.Show("请输入有效的目标章节数", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    TargetChapterCountTextBox.Focus();
                    return;
                }

                if (!int.TryParse(TargetWordsPerChapterTextBox.Text, out int wordsPerChapter) || wordsPerChapter <= 0)
                {
                    MessageBox.Show("请输入有效的每章目标字数", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    TargetWordsPerChapterTextBox.Focus();
                    return;
                }

                TargetChapterCount = chapterCount;
                TargetWordsPerChapter = wordsPerChapter;
            }

            try
            {
                // 创建项目目录
                var projectPath = Path.Combine(ProjectPathTextBox.Text, ProjectNameTextBox.Text);
                if (!Directory.Exists(projectPath))
                {
                    Directory.CreateDirectory(projectPath);
                }

                // 设置返回值
                ProjectName = ProjectNameTextBox.Text.Trim();
                ProjectType = selectedItem?.Tag?.ToString() ?? "Normal";
                ProjectPath = projectPath;
                ProjectDescription = ProjectDescriptionTextBox.Text.Trim();
                CreativeDirection = CreativeDirectionTextBox.Text.Trim();
                IsConfirmed = true;

                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建项目目录失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            IsConfirmed = false;
            DialogResult = false;
            Close();
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            ProjectNameTextBox.Focus();
            ProjectNameTextBox.SelectAll();
        }
    }
}
